package resolver

import (
	"context"
	"net/url"
	"strconv"
	"sync"

	"go-toolkit/library/conf/env"
	"go-toolkit/library/log"
	"go-toolkit/library/naming"

	"github.com/pkg/errors"
)

const scheme = "http"

var (
	errResolveRequired = errors.New("resolve required")
)

// Config is
type Config struct {
	Zone    string
	Cluster string
}

// DynResolver is
type DynResolver struct {
	conf *Config

	rLock     sync.RWMutex
	resolvers map[string]naming.Resolver

	iLock      sync.RWMutex
	localStore map[string]*wrrPicker

	builder naming.Builder
}

// New is
func New(conf *Config, builder naming.Builder) *DynResolver {
	if conf == nil {
		conf = &Config{}
	}
	if conf.Zone == "" {
		conf.Zone = env.Zone
	}
	return &DynResolver{
		conf:       conf,
		resolvers:  map[string]naming.Resolver{},
		localStore: map[string]*wrrPicker{},
		builder:    builder,
	}
}

func (dr *DynResolver) buildResolver(hostname string) (naming.Resolver, error) {
	return dr.builder.Build(hostname, naming.ScheduleNode(dr.conf.Zone)), nil
}

func (dr *DynResolver) resolver(hostname string) (naming.Resolver, error) {
	dr.rLock.RLock()
	resolver, ok := dr.resolvers[hostname]
	dr.rLock.RUnlock()
	if ok {
		return resolver, nil
	}
	newResolver, err := dr.buildResolver(hostname)
	if err != nil {
		return nil, err
	}

	dr.rLock.Lock()
	defer dr.rLock.Unlock()
	resolver, ok = dr.resolvers[hostname]
	if ok {
		newResolver.Close()
		return resolver, nil
	}
	dr.resolvers[hostname] = newResolver
	return newResolver, nil
}

func (dr *DynResolver) disc(hostname string, resolver naming.Resolver) error {
	insMap, ok := resolver.Fetch(context.Background())
	if !ok {
		// log.Error("discovery fetch instance fail(%s)", c.appID)
		return errors.New("failed to fetch instance")
	}
	tinstance, ok := insMap[dr.conf.Zone]
	if !ok {
		for _, value := range insMap {
			tinstance = value
			break
		}
	}
	instance := make([]*naming.Instance, 0, len(tinstance))
	for _, svr := range tinstance {
		nsvr := new(naming.Instance)
		*nsvr = *svr
		cluster := svr.Metadata[naming.MetaCluster]
		if dr.conf.Cluster != "" && dr.conf.Cluster != cluster {
			continue
		}
		instance = append(instance, nsvr)
	}
	log.Info("discovery get %d instances ", len(instance))
	if len(instance) <= 0 {
		return nil
	}
	findSuitable := func(in []string) string {
		for _, v := range in {
			u, err := url.Parse(v)
			if err != nil {
				continue
			}
			if u.Scheme == scheme {
				return u.Host
			}
		}
		return ""
	}
	parseMeta := func(in map[string]string) *md {
		weight, _ := strconv.ParseInt(in["weight"], 10, 64)
		color := in["color"]
		return &md{
			weight: weight,
			color:  color,
		}
	}
	pools := make(map[string]*md)
	for _, svr := range instance {
		addr := findSuitable(svr.Addrs)
		if addr == "" {
			log.Warn("net/http: invalid http address(%s,%s,%v) found!", svr.AppID, svr.Hostname, svr.Addrs)
			continue
		}
		pools[addr] = parseMeta(svr.Metadata)
		log.Info("new http cli %+v instance info %+v", addr, svr)
	}
	dr.storeLocal(hostname, pools)
	return nil
}

func (dr *DynResolver) discproc(hostname string, event <-chan struct{}, resolver naming.Resolver) {
	for {
		if _, ok := <-event; ok {
			dr.disc(hostname, resolver)
			continue
		}
		return
	}
}

func (dr *DynResolver) storeLocal(hostname string, instances map[string]*md) {
	dr.iLock.Lock()
	defer dr.iLock.Unlock()
	dr.localStore[hostname] = Build(instances)
}

func (dr *DynResolver) fromLocalStore(ctx context.Context, hostname string) (string, func(err error), error) {
	dr.iLock.RLock()
	balancer, ok := dr.localStore[hostname]
	dr.iLock.RUnlock()
	if !ok {
		return "", nil, errResolveRequired
	}
	return balancer.Pick(ctx)
}

// ResolveHostname is
func (dr *DynResolver) ResolveHostname(ctx context.Context, hostname string) (string, func(err error), error) {
	addr, done, err := dr.fromLocalStore(ctx, hostname)
	if err == nil {
		return addr, done, nil
	}

	resolver, err := dr.resolver(hostname)
	if err != nil {
		return "", nil, err
	}

	// initial resolve
	event := resolver.Watch()
	select {
	case _, ok := <-event:
		if ok {
			dr.disc(hostname, resolver)
			break
		}
		return "", nil, errors.Errorf("resolve %q canceled", hostname)
	case <-ctx.Done():
		return "", nil, errors.Errorf("resolve %q deadline execeeded", hostname)
	}

	go dr.discproc(hostname, event, resolver)
	return dr.fromLocalStore(ctx, hostname)
}
